package com.seuic.scannerapitest.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.SparseIntArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.seuic.scanner.Scanner;
import com.seuic.scanner.ScannerFactory;
import com.seuic.scannerapitest.R;
import com.seuic.scannerapitest.dao.scanDao;
import com.seuic.scannerapitest.service.ScannerService;

public class MainActivity extends Activity {
	static final String TAG = "ScannerApiTest";
	static final int SCANNER_KEYCODE = 142;
	EditText mEditText;
	ScanReceiver receiver;
	IntentFilter filter;

	private scanDao mscanDao;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_main);

		mscanDao = new scanDao(this);
		// 程序打开的时候调用服务，只用调用一次即可，不需要在每个activity中都调用
		Intent intent = new Intent(MainActivity.this, ScannerService.class);
		startService(intent);

		// 每个activitys要注册接收器，以接收扫描服务传过来的条码
		// 使用自定义广播接收器【action:可以自己定义】
		// 注册和卸载接收器建议放在onResume和onPause中
		receiver = new ScanReceiver();
		filter = new IntentFilter(ScannerService.ACTION);

		init();
	}

	void init() {
		mEditText = (EditText) findViewById(R.id.text);
	}

	@Override
	protected void onResume() {
		super.onResume();
		// 注册接收器
		registerReceiver(receiver, filter);
	}

	@Override
	protected void onPause() {
		// 卸载接收器
		unregisterReceiver(receiver);
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Intent intent = new Intent(MainActivity.this, ScannerService.class);
		stopService(intent);
	}

	public class ScanReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle bundle = intent.getExtras();

			mEditText.append("barcode: "
					+ bundle.getString(ScannerService.BAR_CODE) + "\ntype: "
					+ bundle.getString(ScannerService.CODE_TYPE) + "\nlength: "
					+ bundle.getInt(ScannerService.LENGTH) + "\n");
		//	mscanDao.insert_barcode(ScannerService.BAR_CODE);
		}
	}

}
